package edu.zut.lxc.loveime.keyboard;


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;


import androidx.annotation.Nullable;

import edu.zut.lxc.loveime.MainActivity;
import edu.zut.lxc.loveime.MyApp;
import edu.zut.lxc.loveime.R;

import edu.zut.lxc.loveime.MyInputMethodService;
import edu.zut.lxc.loveime.constants.DemoKeyCode;
import edu.zut.lxc.loveime.util.OpenAIAPI;

import java.util.List;

/**
 * 类说明: 自定义键盘
 *
 * @author qing
 * @time 31/01/2018 17:57
 */
public class MyKeyboardView extends KeyboardView {

    MyInputMethodService service = (MyInputMethodService) getContext();
    //当前输入的连接
 public  InputConnection ic = service.getCurrentInputConnection();



    private OpenAIAPI aiApi;
    private final static String TAG = "MyKeyboardView";



    private  MyApp myApp;
    // 数字键盘／字母键盘／符号键盘
    private Keyboard mKeyboardNum, mKeyboardLetter, mKeyboardSymbol;


    public MyKeyboardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initKeyboardView(context);
    }

    public MyKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


        initKeyboardView(context);

    }

    private void initKeyboardView(Context context) {

        mKeyboardLetter = new Keyboard(context, R.xml.qwerty);
        mKeyboardNum = new Keyboard(context, R.xml.digit);
        mKeyboardSymbol = new Keyboard(context, R.xml.symbol);

        aiApi = new OpenAIAPI();

        myApp = MyApp.getInstance();
        //默认显示字母键盘
        setKeyboard(mKeyboardLetter);
        setOnKeyboardActionListener(new MyOnKeyboardActionListener());


    }


    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        List<Keyboard.Key> keys = getKeyboard().getKeys();
        for (Keyboard.Key key : keys) {
            int code = key.codes[0];
            // LogUtil.e("KEY", "Drawing key with code " + code);
            //ABC
            if (code == DemoKeyCode.CODE_PASTE_SHORT) {
                Drawable dr = getContext().getResources().getDrawable(R.drawable.my_tint);
                dr.setBounds(key.x+5
                        , key.y+10, key.x + key.width, key.y-10 + key.height);
                dr.draw(canvas);
                drawText(canvas,key);

//                drawKeyBackground(R.drawable.keyboard_shift, canvas, key);
            }

            if (code == DemoKeyCode.CODE_PASTE_LONG){
                Drawable dr = getContext().getResources().getDrawable(R.drawable.my_tint_long);
                dr.setBounds(key.x+5
                        , key.y+10, key.x + key.width, key.y-10 + key.height);
                dr.draw(canvas);
                drawText(canvas,key);
            }else if (code == DemoKeyCode.CODE_SPACE){
                Drawable dr = getContext().getResources().getDrawable(R.drawable.my_tint_space);
                dr.setBounds(key.x+5
                        , key.y+10, key.x + key.width, key.y-10 + key.height);
                dr.draw(canvas);
                drawText(canvas,key);

            }else   if (code == DemoKeyCode.CODE_TYPE_SWITCH_INPUT) {

                Drawable dr = getContext().getResources().getDrawable(R.drawable.my_tint_space);
                dr.setBounds(key.x+5
                        , key.y+10, key.x + key.width, key.y-10 + key.height);
                dr.draw(canvas);


                drawKeyBackground(R.drawable.keyboard_switch, canvas, key);
            }else

            if (code == DemoKeyCode.CODE_MY_LOGO) {
                Drawable dr = getContext().getResources().getDrawable(R.drawable.my_tint_space);
                dr.setBounds(key.x+5
                        , key.y+10, key.x + key.width, key.y-10 + key.height);
                dr.draw(canvas);
                drawKeyBackground(R.drawable.my_logo, canvas, key);
            } else if (code == DemoKeyCode.CODE_MY_APP_LABEL) {
                key.label = "追爱键盘";
                Drawable dr = getContext().getResources().getDrawable(R.drawable.my_tint_space);
                dr.setBounds(key.x+5
                        , key.y+10, key.x + key.width, key.y-10 + key.height);
                dr.draw(canvas);
                drawText(canvas,key);
            }


            //完成 return
            else if (code == Keyboard.KEYCODE_DONE) {
                drawKeyBackground(R.drawable.keyboard_enter, canvas, key);
            } else if (code == DemoKeyCode.CODE_PASTE_LONG) {
                key.label = "请粘贴TA的话";

            }

            // 符号 数字 abc
            else if (code == DemoKeyCode.CODE_TYPE_SYMBOL || code == DemoKeyCode.CODE_TYPE_QWERTY || code == DemoKeyCode.CODE_TYPE_NUM) {
                drawKeyBackground(R.drawable.keyboard_gray, canvas, key);
                drawText(canvas, key);
            }
        }
    }


//    @Override
//    public boolean onTouchEvent(MotionEvent me) {
//
//
//        float x = me.getX();
//        float y = me.getY();
//        switch (me.getAction()) {
//
//            case MotionEvent.ACTION_DOWN:
//                mDownX = x;
//                mDownY = y;
//                break;
//            case MotionEvent.ACTION_MOVE:
//                setPreviewEnabled(false);
//                //滑动距离小于10dp时不隐藏键盘预览 大于10dp时隐藏键盘按键预览
////                if (Math.abs(x - mDownX) > MyUtil.dp2px(10) || Math.abs(y - mDownY) > MyUtil.dp2px(10)) {
////                    //取消预览
////                    setPopupOffset(0, MyUtil.dp2px(0));
////                }
//                break;
//        }
//
//
//        return super.onTouchEvent(me);
//
//    }

    /**
     * 绘制按键背景
     *
     * @param drawableId
     * @param canvas
     * @param key
     */
    private void drawKeyBackground(int drawableId, Canvas canvas, Keyboard.Key key) {
        if (key.codes[0] == 300){

        }
        Drawable npd = (Drawable) getContext().getResources().getDrawable(drawableId);
        int[] drawableState = key.getCurrentDrawableState();
        if (key.codes[0] != 0) {
            npd.setState(drawableState);
        }
        //绘制按键背景  加上 MyUtil.dp2px(4)
        npd.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
        npd.draw(canvas);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 绘制文字
     *
     * @param canvas
     * @param key
     */
    private void drawText(Canvas canvas, Keyboard.Key key) {
        Rect bounds = new Rect();
        bounds.set(key.x, key.y, key.x + key.width, key.y + key.height);
        Paint paint = new Paint();
        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(45);

        paint.setAntiAlias(true);
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        if (Keyboard.KEYCODE_DONE == key.codes[0]) {
            paint.setColor(Color.WHITE);
        } else if (key.codes[0]==DemoKeyCode.CODE_PASTE_LONG) {
            paint.setColor(Color.rgb(210, 249, 46));
        }  else{
            paint.setColor(Color.rgb(0,0,0));
        }
        if (key.label != null) {
            paint.getTextBounds(key.label.toString(), 0, key.label.toString().length(), bounds);
            canvas.drawText(key.label.toString(), key.x + (key.width / 2), (key.y + key.height / 2) + bounds
                    .height() / 2, paint);
        }
    }


    class MyOnKeyboardActionListener implements OnKeyboardActionListener {


        //是否是大写字母
        private boolean mIsUpper;

        @Override
        public void onPress(int primaryCode) {

        }

        @Override
        public void onRelease(int primaryCode) {

        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {


            List<Keyboard.Key> keys = getKeyboard().getKeys();

            //键盘服务
            String clipboardContent = getClipboardContent(getContext());
            switch (primaryCode) {
                //删除
                case Keyboard.KEYCODE_DELETE:
                    ic.deleteSurroundingText(1, 0);
                    break;
                //完成
                case Keyboard.KEYCODE_DONE:
                    ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER));
                    break;
                case DemoKeyCode.CODE_TYPE_SWITCH_INPUT:
                    //弹出切换键盘的按钮
                    ((InputMethodManager)myApp.getSystemService(Context.INPUT_METHOD_SERVICE)).showInputMethodPicker();
                    break;
                case DemoKeyCode.CODE_PASTE_LONG :
                case DemoKeyCode.CODE_PASTE_SHORT:

                    SharedPreferences sharedPreferences = getContext().getSharedPreferences("user_info",Context.MODE_PRIVATE);
                    if (clipboardContent==null){
                        //弹出提示
                        Toast.makeText(getContext(),"您还没有复制~",Toast.LENGTH_SHORT);
                    }else {

                        for (Keyboard.Key key : keys){

                            if (key.codes[0] == DemoKeyCode.CODE_PASTE_LONG){
                                key.label = clipboardContent;
                            }
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("clipboardContent",clipboardContent);
                            editor.commit();
                        }
                    }
                    break;

                case DemoKeyCode.CODE_CLEAR:
                    CharSequence textBeforeCursor = ic.getTextBeforeCursor(1000, 0);
                    int length = textBeforeCursor.length();
                    if (length > 0) {
                        ic.deleteSurroundingText(length, 0);
                    }

                    break;
                    //一般文本
                default:
                    char inputChar = (char) primaryCode;
                    ic.commitText(String.valueOf(inputChar), 1);
            }
        }
        @Override
        public void onText(CharSequence text) {

        }

        @Override
        public void swipeLeft() {

        }

        @Override
        public void swipeRight() {

        }

        @Override
        public void swipeDown() {

        }

        @Override
        public void swipeUp() {

        }
    }

//    MyHandler handler = new MyHandler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg.what == 1){
//
//            }
//        }
//    };

    /**
     * 获取剪切板上的内容
     */
    @Nullable
    public static String getClipboardContent(Context context) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm != null) {
            ClipData data = cm.getPrimaryClip();
            if (data != null && data.getItemCount() > 0) {
                ClipData.Item item = data.getItemAt(0);
                if (item != null) {
                    CharSequence sequence = item.coerceToText(context);
                    if (sequence != null) {
                        return sequence.toString();
                    }
                }
            }
        }
        return null;
    }



}
